package com.sicurezza.secUtility;

import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.util.Random;

import android.content.Context;
import android.widget.Toast;

public class KeySaver {

	public static void saveKey(Context context, byte[] key, String name){
		try {
			KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
			ks.setKeyEntry(name, key, null);
		} catch (KeyStoreException e) {
			Toast.makeText(context, "KeyStore non trovato", Toast.LENGTH_LONG).show();
		}
	}
	
	public static byte[] retrieveKey(Context context, String name){
		byte[] res = null;
		try {
			KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
			res = ks.getKey(name, null).getEncoded();
		} catch (KeyStoreException e) {
			Toast.makeText(context, "KeyStore non trovato", Toast.LENGTH_LONG).show();
		} catch (UnrecoverableKeyException e) {
			Toast.makeText(context, "Chiave non recuperabile", Toast.LENGTH_LONG).show();
		} catch (NoSuchAlgorithmException e) {
			Toast.makeText(context, "Algoritmo non valido", Toast.LENGTH_LONG).show();
		}
		return res;
	}
	
	public static byte[] saltGenerator(){
		Random rdn = new SecureRandom();
		byte[] salt = new byte[32];
		rdn.nextBytes(salt);
		return salt;
	}
	
	public static String returnKeyAsHash(byte[] key,byte[] salt, String alghoritm, Context context){
		byte[] newKey = new byte[key.length + salt.length];
		System.arraycopy(key, 0, newKey, 0, key.length);
		System.arraycopy(salt, 0, newKey, key.length, salt.length);
		HashMaker hm = new HashMaker(newKey, alghoritm, context);
		return hm.hashMake();
	}

}
